<template>
  <el-dialog title="选择设备" :visible.sync="dialogVisible" 
    :lock-scroll="false" 
    :append-to-body="true" 
    @opened="handleDialogOpened">
    <el-input placeholder="输入关键字进行过滤" v-model="filterText"></el-input>
    <el-tree ref="deviceTree"
      :data="deviceData"
      node-key="id"
      default-expand-all
      highlight-current
      :expand-on-click-node="false"
      :show-checkbox="showCheckbox"
      :filter-node-method="filterNode" 
      style="height: 50vh; overflow: auto;"
    >
      <span slot-scope="{ node, data }">
        <span>
            <i :class="getTreeIcon(data)"></i>&nbsp;&nbsp;{{ node.label }}
        </span>              
      </span>
    </el-tree>
    <div slot="footer">
      <el-button @click="dialogVisible = false">取 消</el-button>
      <el-button type="primary" @click="handleClick">确 定</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { getSubstationTree, getBusTree, getLineTree, getBreakerTree,
  getChannelTree, getConditionTree } from '@/api/draw.js'
import ConstantUtil from '@/utils/graph-utils/constantUtil.js'
import UIUtil from '@/utils/graph-utils/uiUtil'

export default {
  name: 'SelectDeviceDialog',
  props: [],
  data() {
    return {
      filterText: '',
      dialogVisible: false,
      deviceData: [],

      graphNode: null,
      showCheckbox: false,
      currentKey: '',
      checkedKeys: []
    }
  },
  watch: {
    filterText(val) {
      this.$refs.deviceTree.filter(val)
    }
  },
  methods: {
    initDialogData() {
      this.filterText = ''
      this.deviceData = []
      this.showCheckbox = false
      this.currentKey = ''
      this.checkedKeys = []
    },

    showDialog(node) {
      if (!node || !node.data) {
        return
      }
      this.initDialogData()
      this.graphNode = node
      this.showCheckbox = ConstantUtil.isConditionType(node.data.metaType)

      // 获取当前节点已经配置的数据信息
      const metaType = node.data.metaType
      if (ConstantUtil.isElectricType(metaType) || ConstantUtil.isFaultType(metaType)) {
        this.currentKey = node.data.id
      } else if (ConstantUtil.isChannelType(metaType) && node.data.savedRtus) {
        this.currentKey = node.data.savedRtus
      } else if (ConstantUtil.isConditionType(metaType) && node.data.savedRtus) {
        const values = node.data.savedRtus.split(',')
        for (const value of values) {
          const innerValues = value.split(':')
          if (innerValues.length > 0) {
            this.checkedKeys.push(innerValues[0])
          }
          this.checkedKeys.push(value)
        }
      }

      this.dialogVisible = true
    },

    getTreeIcon(nodeData) {
      const type = nodeData.properties ? nodeData.properties.type : ''
      if (!type) {
        return ''
      }
      let iconClass = ''
      switch (type) {
        case 'district':
          iconClass = 'iconfont icon-district'
          break
        case 'substation':
          iconClass = 'iconfont icon-substation'
          break
        case 'bus':
          iconClass = 'iconfont icon-bus'
          break
        case 'line':
          iconClass = 'iconfont icon-line'
          break
        case 'tline':
          iconClass = 'iconfont icon-tline'
          break
        case 'breaker':
          iconClass = 'iconfont icon-breaker'
          break
        case 'device':
          iconClass = 'iconfont icon-device'
          break
        case 'channel':
          iconClass = 'el-icon-s-help'
          break
        case 'condition':
          iconClass = 'el-icon-s-help'
          break
      }
      return iconClass
    },

    filterNode(value, data) {
      if (!value) return true
      return data.label.indexOf(value) !== -1
    },

    initTreeData() {
      const self = this
      self.deviceData = []
      const metaType = self.graphNode.data.metaType
      return new Promise((resolve, reject) => {
        // 从后台加载厂站内的电力设备
        if (ConstantUtil.isSubstationType(metaType) || ConstantUtil.isFaultType(metaType)) {
          getSubstationTree().then(response => {
            self.deviceData.push(response.data)
            resolve()
          })
        } else if (ConstantUtil.isBusType(metaType)) {
          getBusTree().then(response => {
            self.deviceData.push(response.data)
            resolve()
          })
        } else if (ConstantUtil.isLineType(metaType) || self.graphNode.isEdge()) {
          getLineTree().then(response => {
            self.deviceData.push(response.data)
            resolve()
          })
        } else if (ConstantUtil.isBreakerType(metaType)) {
          getBreakerTree().then(response => {
            self.deviceData.push(response.data)
            resolve()
          })
        } else if (ConstantUtil.isChannelType(metaType)) {
          getChannelTree().then(response => {
            self.deviceData.push(response.data)
            resolve()
          })
        } else if (ConstantUtil.isConditionType(metaType)) {
          getConditionTree().then(response => {
            self.deviceData.push(response.data)
            resolve()
          })
        }
      })
    },

    handleDialogOpened() {
      const self = this
      self.initTreeData().then(resolve => {
        if (self.showCheckbox) {
          self.$refs.deviceTree.setCheckedKeys(self.checkedKeys)
        } else {
          self.$refs.deviceTree.setCurrentKey(self.currentKey)
        }
      }).catch(() => {})
    },

    handleClick() {
      const self = this
      let nodes
      let type = ''
      if (self.showCheckbox) {
        nodes = self.$refs.deviceTree.getCheckedNodes(true)
        for (const node of nodes) {
          const nodeType = node.properties ? node.properties.type : ''
          if (type.indexOf(nodeType) === -1) {
            type += nodeType
          } else {
            type = nodeType
          }
        }
      } else {
        nodes = self.$refs.deviceTree.getCurrentNode()
        type = nodes.properties ? nodes.properties.type : ''
      }

      let validNodes = false
      const metaType = self.graphNode.data.metaType
      if (ConstantUtil.isSubstationType(metaType) || ConstantUtil.isFaultType(metaType)) {
        validNodes = type === 'substation'
      } else if (ConstantUtil.isBusType(metaType)) {
        validNodes = type === 'bus'
      } else if (ConstantUtil.isLineType(metaType) || self.graphNode.isEdge()) {
        validNodes = type === 'line'
      } else if (ConstantUtil.isBreakerType(metaType)) {
        validNodes = type === 'breaker'
      } else if (ConstantUtil.isChannelType(metaType)) {
        validNodes = type === 'channel'
      } else if (ConstantUtil.isConditionType(metaType)) {
        validNodes = type === 'condition'
      }

      if (validNodes) {
        this.$emit('submitOk', nodes)
        this.dialogVisible = false
      } else {
        UIUtil.failMessage('请选择合适的节点')
      }
    }
  }
}
</script>